package org.example.reducejoin;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import org.codehaus.jackson.map.util.BeanUtil;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

public class TableReducer extends Reducer<Text, TableBean, TableBean, NullWritable> {
    @Override
    protected void reduce(Text key, Iterable<TableBean> values, Reducer<Text, TableBean, TableBean, NullWritable>.Context context) throws IOException, InterruptedException {
        try {
            List<TableBean> orderBeans = new ArrayList<>();
            TableBean tableBean = new TableBean();
            TableBean pdBean = new TableBean();
            for (TableBean value : values) {
                if ("order".equals(value.getFlag())) {

                    BeanUtils.copyProperties(tableBean, value);
                    orderBeans.add(tableBean);
                } else if ("pd".equals(value.getFlag())) {

                    BeanUtils.copyProperties(pdBean, value);
                }
            }

            for (TableBean orderBean : orderBeans) {
                orderBean.setPname(pdBean.getPname());
                context.write(orderBean, NullWritable.get());
            }


        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
}

